package com.xihuanjun.util;

import com.xihuanjun.exception.FiledIsNullException;
import com.xihuanjun.validate.annotation.Validate;
import com.xihuanjun.validate.enums.ValidateType;

import java.lang.reflect.Field;
import java.util.Arrays;

/**
 * @author: 江溪浣
 * @createDate: 2022/10/17 11:51
 * @description:
 */
public class ValidateUtils {

    /**
     * 验证一个对象是否符合必填项规范
     * @param object 要验证的对象
     * @param clazz 对象的类结构
     * @param validateType 验证场景，添加还是修改
     */
    public static void validate(Object object, Class clazz, ValidateType validateType) {
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            Validate annotation = field.getAnnotation(Validate.class);
            if(annotation!=null){//属性有验证标记
                if(Arrays.asList(annotation.type()).contains(validateType)){//如果标记的type里有要验证的type
                    try {
                        if(field.get(object)==null){
                            throw new FiledIsNullException(annotation.value()+"必填");
                        }else{//不是null
                            System.out.println("是否是string："+(field.getType()==String.class));
                            System.out.println("value："+(field.get(object)));
                            if(field.getType()==String.class && field.get(object).toString().trim().equals("")){
                                throw new FiledIsNullException(annotation.value()+"必填");
                            }
                        }
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}
